<?php
/**
 * DolphinGTK - phpGtk framework
 *
 * @package    DolphinGTK
 * @author     Askarov Ruslan
 * @copyright  Askarov Ruslan (c) 2010.
 * @link       http://groups.google.com/group/dolphingtk
 * @license    http://www.opensource.org/licenses/gpl-license.php GPL
 * @version    0.1
 * @since      PHP v.: 5.2.1
 * @subpackage desktop
 * @category   library
 * @filesource
 */


final class Widgets
{

  public static $_ip_enter;


  /**
   * Метод по умолчанию. Разрешаем использование
   * методов, только как статические.
   *
   * @access public
   * @return void
   */
  public function __construct()
  {
    throw new Exception(
      'Class "Widgets" used only static methods. And cannot be constructed!'
    );
  }




  /**
   * Метод для создания графической кнопки
   *
   * @access public
   * @param  string $label
   * @param  string $icon
   * @param  array/string $foo
   * @param  array $size
   * @return gtk button
   */
  public static function button( $label, $icon, $foo, $size = false )
  {
    if( empty($label) ) {
      print "Enter button label!\n";
      return false;
    }

    // аб. путь
    if( !defined('BASE_DIR') ) {
      $path = './';
    } else {
      $path = BASE_DIR;
    }

    if( $icon && file_exists($path.$icon) )
    {
      $img = GtkImage::new_from_file($path.$icon);
    }
    elseif( $icon && get_icon( $icon ) )
    {
      $img = GtkImage::new_from_stock(
        get_icon( $icon ),
        Gtk::ICON_SIZE_BUTTON
      );
    }

    if( count($foo) > 2 ) {
      $foon = array_slice($foo,0,2);
      $arg = array_slice($foo,2);
      $arg = "'".implode("', '", $arg) . "'";
    } else {
      $foon = $foo;
    }

    $button = new GtkButton();

    if( is_array($size) && count($size) == 2 ) {
      $button->set_size_request($size[0], $size[1]);
    }
    
    if( !empty($arg) ) {
      eval('$button->connect(\'clicked\', $foon, '.$arg.');');
    } else {
      $button->connect('clicked', $foon);
    }
    

    $button_hbox = new GtkHBox();
    $button->add($button_hbox);
    
    if( $img )
    {
      $button_hbox->pack_start($img, 0, 0);
      $button_hbox->pack_start(new GtkLabel(), 0, 0);
    }
    
    $button_hbox->pack_start(new GtkLabel($label), 0, 0);

    return $button;
  }




  /**
   * Метод для создания диалога, выбора файла или директории
   *
   * @access public
   * @param  string $title
   * @param  string $type
   * @param  array $ext
   * @return string/bool
   */
  public static function choise( $title, $type = 'dir', $ext = false )
  {
    if( empty($title) ) return false;

    if( $type == 'file_open' ) {
      $type = Gtk::FILE_CHOOSER_ACTION_OPEN;
    } elseif( $type == 'file_save' ) {
      $type = Gtk::FILE_CHOOSER_ACTION_SAVE;
    } elseif( $type == 'create_folder' ) {
      $type = Gtk::FILE_CHOOSER_ACTION_CREATE_FOLDER;
    } else {
      $type = Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER;
    }

    $dialog = new GtkFileChooserDialog( 
      $title, null, $type, array(
        Gtk::STOCK_OK, Gtk::RESPONSE_OK,
        Gtk::STOCK_CANCEL, Gtk::RESPONSE_CANCEL
      )
    );

    if(  is_array($ext) && count($ext) > 0 )
    {
      $filters = new GtkFileFilter();
      foreach( $ext as $f ) {
        $filters->add_pattern($f);
      }
      $dialog->set_filter($filters);
    }

    $dialog->show_all();

    if( $dialog->run() == Gtk::RESPONSE_OK ) {
      $return = $dialog->get_filename();
    }
    else {
      $return = false;
    }

    return $return;
  }




  /**
   * Метод для графической заставки
   *
   * @access public
   * @param  int $time
   * @param  string $image
   * @return void
   */
  public static function splash( $time, $image )
  {
    if( $image && file_exists($image) && is_numeric($time) && $time > 100 )
    {
      $dialog = new GtkWindow(GTK::WINDOW_POPUP);
      $dialog->set_position(Gtk::WIN_POS_CENTER);
      $dialog->set_resizable(false);
      $dialog->set_decorated(false);
      $dialog->set_skip_taskbar_hint(true);
      $dialog->set_skip_pager_hint(true);
      $dialog->set_type_hint(Gdk::WINDOW_TYPE_HINT_SPLASHSCREEN);

      $pixbuf = GdkPixbuf::new_from_file($image);
      list($pixmap, $mask) = $pixbuf->render_pixmap_and_mask();
      list($width, $height) = $pixmap->get_size();
      $dialog->set_app_paintable(true);
      $dialog->set_size_request($width, $height);
      $dialog->realize();

      if($mask instanceof GdkPixmap) {
        $dialog->shape_combine_mask($mask, 0, 0);
      }

      $dialog->window->set_back_pixmap($pixmap, false);
      $dialog->show_all();

      for( $i = 0; $i < $time; $i ++ ) {
        while ( Gtk::events_pending() )
        Gtk::main_iteration();
      }

      $dialog->hide_all();
      $dialog->destroy();
    }
  }




  /**
   * Метод для ввода IPv4 адреса.
   *
   * @access public
   * @return void
   */
  public static function ipv4( $ip = '' )
  {
    $hbox = new GtkHBox();
    $enter = array();
    $set = false;

    if( !empty($ip) )
    {
      $ip = explode('.',$ip);
      if( count($ip) == 4 ) {
        $set = $ip;
      }
    }

    for( $i = 0; $i < 4; $i ++ )
    {
      self::$_ip_enter[$i] = new GtkEntry();
      self::$_ip_enter[$i]->set_property('xalign',0.5);
      self::$_ip_enter[$i]->set_property('has-frame',0);
      self::$_ip_enter[$i]->set_size_request(30, -1);

      if( is_array($set)) {
        self::$_ip_enter[$i]->set_text($set[$i]);
      } else {
        self::$_ip_enter[$i]->set_text('0');
      }
      
      self::$_ip_enter[$i]->connect('key-press-event',array('Widgets','_on_button_down'),$i);
      self::$_ip_enter[$i]->connect('key-release-event',array('Widgets','_on_button_up'),$i);

      $hbox->pack_start(self::$_ip_enter[$i],0);
      if($i != 3) {
        $hbox->pack_start(new GtkLabel('.'),0);
      }
    }

    $eventBox = new GtkEventBox();
    $eventBox->add($hbox);
    $eventBox->modify_bg(Gtk::STATE_NORMAL,GdkColor::parse('#ffffff'));

    return $eventBox;
  }



  public static function _on_button_down($entry, $event, $entryId)
  {
    if(chr($event->keyval) == '.' && $event->keyval != Gdk::KEY_Tab) {
      $sTxt = $entry->get_text();

      if( $entryId == 3 ) {
        self::$_ip_enter[0]->grab_focus();
      } else {
        self::$_ip_enter[$entryId + 1]->grab_focus();
      }
      return true;
    } else {
      return false;
    }
  }



  public static function _on_button_up($entry, $event, $entryId)
  {
    if( strlen(trim($entry->get_text())) == 3 && chr($event->keyval) != '.' && $event->keyval != Gdk::KEY_Tab )
    {
      if( $entryId == 3 ) {
        self::$_ip_enter[0]->grab_focus();
      } else {
        self::$_ip_enter[$entryId + 1]->grab_focus();
      }
    }

    if( !is_numeric($entry->get_text()) ) {
      $entry->set_text('0');
    }

    if( trim($entry->get_text()) > 255 ) {
      $entry->set_text('255');
    }
  }

}
?>
